using Lzfy_His_Service.Models;
using Oracle.ManagedDataAccess.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;

namespace Lzfy_His_Service.Services
{
    /// <summary>
    /// 患者沟通记录查询服务实现
    /// </summary>
    public class PatientCommunicationService : IPatientCommunicationService
    {
        private readonly IOracleConnectionFactory _oracleConnectionFactory;
        private readonly ILogger<PatientCommunicationService> _logger;

        public PatientCommunicationService(
            IOracleConnectionFactory oracleConnectionFactory,
            ILogger<PatientCommunicationService> logger)
        {
            _oracleConnectionFactory = oracleConnectionFactory;
            _logger = logger;
        }

        /// <summary>
        /// 通过患者电话查询沟通记录
        /// </summary>
        /// <param name="phoneNumber">患者电话号码</param>
        /// <returns>患者沟通记录列表</returns>
        public async Task<List<PatientCommunicationRecord>> GetCommunicationRecordsByPhoneAsync(string phoneNumber)
        {
            var result = new List<PatientCommunicationRecord>();

            try
            {
                using var connection = _oracleConnectionFactory.CreateConnection();
                if (connection is OracleConnection oracleConn)
                {
                    await oracleConn.OpenAsync();
                }
                else
                {
                    connection.Open();
                }

                var query = @"
                    SELECT t1.pat_name as PatName,
                           t1.patient_id as PatientId,
                           t1.phone_number as PhoneNumber,
                           t1.id_number as IdNumber,
                           t1.contact_time1 as ContactTime1,
                           t1.notes1 as Notes1,
                           t2.fullname as FullName,
                           t1.balance as Balance,
                           t3.balance as RecentBalance,
                           t1.sex as Sex
                      FROM pca.lzfy_refund_task_detail t1
                      JOIN pca.lzfy_refund_task_master t2
                        ON t1.master_id = t2.id
                      JOIN pca.pca_prepay_account_master t3
                        ON t1.account_id = t3.account_id
                     WHERE t1.phone_number = :phoneNumber";

                var records = await connection.QueryAsync<PatientCommunicationRecord>(query, new { phoneNumber });
                result = records.ToList();

                _logger.LogInformation("查询患者沟通记录成功，电话: {PhoneNumber}，记录数: {Count}", phoneNumber, result.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询患者沟通记录失败，电话: {PhoneNumber}", phoneNumber);
                throw;
            }

            return result;
        }
    }
}